package org.jivesoftware.openfire.plugin;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.TimerTask;

import org.apache.commons.codec.binary.Base64;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.Log;
import org.jivesoftware.util.TaskEngine;
import org.jivesoftware.openfire.MessageRouter;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.container.Plugin;
import org.jivesoftware.openfire.container.PluginManager;
import org.jivesoftware.openfire.event.SessionEventDispatcher;
import org.jivesoftware.openfire.event.SessionEventListener;
import org.jivesoftware.openfire.interceptor.InterceptorManager;
import org.jivesoftware.openfire.interceptor.PacketInterceptor;
import org.jivesoftware.openfire.interceptor.PacketRejectedException;
import org.jivesoftware.openfire.session.Session;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;

/**
 * MotD (Message of the Day) plugin.
 * 
 * @author <a href="mailto:ryan@version2software.com">Ryan Graham</a>
 */
public class MotDPlugin implements Plugin, PacketInterceptor {
   private static final String SUBJECT = "plugin.motd.subject";
   private static final String MESSAGE = "plugin.motd.message";
   private static final String ENABLED = "plugin.motd.enabled";
   private InterceptorManager interceptorManager;
   private JID serverAddress;
   private MessageRouter router;

   private MotDSessionEventListener listener = new MotDSessionEventListener();
   
   public MotDPlugin() {
       interceptorManager = InterceptorManager.getInstance();
   }
   
   public void initializePlugin(PluginManager manager, File pluginDirectory) {
       
      Log.info("Packet Filter loaded...");
      interceptorManager.addInterceptor(this); 
      serverAddress = new JID(XMPPServer.getInstance().getServerInfo().getXMPPDomain());
      router = XMPPServer.getInstance().getMessageRouter();
      
      SessionEventDispatcher.addListener(listener);
   }

   public void destroyPlugin() {
      SessionEventDispatcher.removeListener(listener);
      
      listener = null;
      serverAddress = null;
      router = null;
   }

   public void setSubject(String message) {
      JiveGlobals.setProperty(SUBJECT, message);
   }

   public String getSubject() {
      return JiveGlobals.getProperty(SUBJECT, "Message of the Day");
   }

   public void setMessage(String message) {
      JiveGlobals.setProperty(MESSAGE, message);
   }

   public String getMessage() {
      return JiveGlobals.getProperty(MESSAGE, "Big Brother is watching.");
   }

   public void setEnabled(boolean enable) {
      JiveGlobals.setProperty(ENABLED, enable ? Boolean.toString(true) : Boolean.toString(false));
   }

   public boolean isEnabled() {
      return JiveGlobals.getBooleanProperty(ENABLED, false);
   }

   private class MotDSessionEventListener implements SessionEventListener {
      public void sessionCreated(Session session) {         
         if (isEnabled()) {
             
            final Message message = new Message();
            message.setTo(session.getAddress());
            message.setFrom(serverAddress);
            message.setSubject(getSubject());
            message.setBody(getMessage());

            TimerTask messageTask = new TimerTask() {
               public void run() {
                  router.route(message);
               }
            };

            TaskEngine.getInstance().schedule(messageTask, 5000);
         }
      }

      public void sessionDestroyed(Session session) {
         //ignore
      }

      public void resourceBound(Session session) {
         // Do nothing.
      }

      public void anonymousSessionCreated(Session session) {
         //ignore
      }

      public void anonymousSessionDestroyed(Session session) {
         //ignore
      }
   }

    @Override
    public void interceptPacket(Packet packet, Session session, boolean incoming,
        boolean processed) throws PacketRejectedException {
       
       Message message = (Message) packet;
       String userSendMessage = message.getBody();
       String sender = message.getFrom().toBareJID();
       //String sender = message.getFrom();
       System.out.println("*"+sender+"*"); 
       String username;
       if(sender.contains("achala")){
    	   
    	   username = "harini_sync";
    	   System.out.println("username"+username);
    	   setTwitter(username,"pass123", userSendMessage );
       }
       if(sender.contains("nilufa")){
    	   username = "nilufa_sync";
       	   System.out.println("username"+username);
       	   setTwitter(username,"pass123", "@harini_sync "+userSendMessage );
       }
       else{
    	   username = "synchrona";
    	   System.out.println("username"+username);
    	   setTwitter(username,"pass123", userSendMessage );
       }
       	   
       
    }
   
   
   private void setTwitter(String username, String password, String message) {
// TODO Auto-generated method stub
  URL url = null;
try {
url = new URL("https://twitter.com/statuses/update.xml");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

      connection.setDoInput(true);
      connection.setDoOutput(true);
      connection.setUseCaches(false);

      String authorization = username + ":" + password;
      Base64 en = new Base64();
      String encoded = new String
                (en.encode(authorization.getBytes())).trim();
      connection.setRequestProperty("Authorization", "Basic " + encoded);

      OutputStreamWriter out = null;
try {
out = new OutputStreamWriter(
          connection.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      try {
out.write("status=" + URLEncoder.encode(message, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

      BufferedReader in = null;
try {
in = new BufferedReader(
          new InputStreamReader(
                  connection.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      String response;
      try {
while ((response = in.readLine()) != null) {
     // System.out.println(response);
  }
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
      try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
 
}

   
   
   
}
